package controller

import (
	"lion-passport/internal/dao/model"
	"lion-passport/internal/service"
	"lion-passport/internal/types"
	"lion-passport/internal/utils"
	"lion-passport/internal/utils/log"
	"net/http"

	"github.com/gin-gonic/gin"
)

func CreateUserHandler(c *gin.Context) {
	var req types.UserCreateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		log.LogrusObj.Infoln(err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request format"})
		return
	}

	userInfo, ok := utils.FromContext(c.Request.Context())
	if !ok {
		c.JSON(http.StatusOK, utils.RespError(305209, "user id not found in context"))
		return
	}
	
	log.LogrusObj.Infof("Creating user with ID: %d, Nickname: %s, Avatar: %s, Phone: %s", userInfo.Id, req.Nickname, req.Avatar, req.Phone)

	user := &model.User{
		UserID:   userInfo.Id,
		Nickname: req.Nickname,
		Avatar:   req.Avatar,
		Phone:    req.Phone,
	}

	createdUser, err := service.CreateUser(user, c.Request.Context())
	if err != nil {
		log.LogrusObj.Infoln(err)
		c.JSON(http.StatusOK, utils.RespError(305110, err.Error()))
		return
	}

	c.JSON(http.StatusOK, createdUser)
}

func UpdateUserHandler(c *gin.Context) {
	var req types.UserCreateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		log.LogrusObj.Infoln(err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request format"})
		return
	}

	userInfo, ok := utils.FromContext(c.Request.Context())
	if !ok {
		c.JSON(http.StatusOK, utils.RespError(305209, "user id not found in context"))
		return
	}
	
	log.LogrusObj.Infof("Updating user with ID: %d, Nickname: %s, Avatar: %s, Phone: %s", userInfo.Id, req.Nickname, req.Avatar, req.Phone)

	user := &model.User{
		UserID:   userInfo.Id,
		Nickname: req.Nickname,
		Avatar:   req.Avatar,
		Phone:    req.Phone,
	}

	updatedUser, err := service.UpdateUserById(user.UserID, user, c.Request.Context())
	if err != nil {
		log.LogrusObj.Infoln(err)
		c.JSON(http.StatusOK, utils.RespError(305110, err.Error()))
		return
	}

	c.JSON(http.StatusOK, updatedUser)
}

func GetUserByIdHandler(c *gin.Context) {
	userInfo, ok := utils.FromContext(c.Request.Context())
	if !ok {
		c.JSON(http.StatusOK, utils.RespError(305209, "user id not found in context"))
		return
	}
	log.LogrusObj.Infof("Fetching user with ID: %d", userInfo.Id)

	user, err := service.GetUserByUid(userInfo.Id, c.Request.Context())
	if err != nil {
		log.LogrusObj.Infoln(err)
		c.JSON(http.StatusOK, utils.RespError(305110, err.Error()))
		return
	}

	if user == nil {
		log.LogrusObj.Infoln("User not found")
		c.JSON(http.StatusOK, utils.RespError(305110, "user not found"))
		return
	}

	c.JSON(http.StatusOK, user)
}
